package com.tokenplus.thai.utils

import android.graphics.Bitmap
import android.graphics.Color
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import java.util.*


/** 条形码工具类 */
object QRCodeUtil {

    /** 生成条形码 */
    fun generateBarCode(imgWidth: Int, imgHeight: Int, content: String): Bitmap? {
        try {
            val bitMatrix =
                MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, imgWidth, imgHeight)
            val width = bitMatrix.width
            val height = bitMatrix.height
            val pixels = IntArray(width * height)
            for (y in 0 until height) {
                val offset = y * width
                for (x in 0 until width) {
                    pixels[offset + x] = if (bitMatrix[x, y]) -0x1000000 else -0x1
                }
            }
            val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height)
            return bitmap
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    }

    /** 生成二维码 */
    fun generateQRCode(imgWidth: Int, imgHeight: Int, content: String): Bitmap? {
        val hints: MutableMap<EncodeHintType, Any?> =
            EnumMap(com.google.zxing.EncodeHintType::class.java)
        // 支持中文配置
        hints[EncodeHintType.CHARACTER_SET] = "UTF-8"
        hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H
        try {
            val bitMatrix = MultiFormatWriter().encode(
                content, BarcodeFormat.QR_CODE, imgWidth, imgHeight)
            val bitmap = Bitmap.createBitmap(imgWidth, imgHeight, Bitmap.Config.ARGB_8888)
            for (x in 0 until imgWidth) {
                for (y in 0 until imgHeight) {
                    bitmap.setPixel(x, y, if (bitMatrix[x, y]) Color.BLACK else Color.WHITE)
                }
            }

            return bitmap
        } catch (e: WriterException) {
            e.printStackTrace()
        }
        return null
    }
}